package vn.kiemviec.app.task;

import org.json.JSONObject;
import org.w3c.dom.Element;

import vn.kiemviec.app.utils.LogTools;
import vn.kiemviec.app.utils.XmlUtils;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.view.KeyEvent;

public abstract class CBGetDetailsTask<E> extends AsyncTask<Object, Object, Object>{

	public interface CBDetailsTaskListener<E>{
		public void onSuccessfull(E listEntry);
		public void onError(int error);
	}
	
	
	private CBDetailsTaskListener<E> mHandler;
	public void setOnTaskListener(CBDetailsTaskListener<E> ev){
		mHandler = ev;
	}
	
	public abstract String onGetApiUrl();
	public abstract E getEntry(JSONObject jb);
	
	private boolean IsSuccessful;
	private E mEntry;
	
	protected ProgressDialog dialog;
	private String dialogMessage = "loading....";
	private boolean enabledProgressDialog = true;
	private Context mContext;
	
	public CBGetDetailsTask(Context context){
		mContext = context;
	}
	
	public void setEnableProgress(boolean value){
		enabledProgressDialog = true;
	}
	
	public void setProgressMessage(String msg){
		
	}
	
	public void setProgressMessage(int msgRes){
		
	}
	
	@Override
	protected void onPreExecute() {
		
		if(!enabledProgressDialog) return;
		
		String message = dialogMessage;
		
		dialog = ProgressDialog.show(mContext, null, message);
		dialog.setCancelable(false);
		dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_SEARCH) {
					return true;
				}
				return false;
			}
		});
	}
	
	@Override
	protected Object doInBackground(Object... arg0) {
		// TODO Auto-generated method stub
		try {
			
			Element root = XmlUtils.getXmlRootByUrl(onGetApiUrl());
			String status = root.getElementsByTagName("status").item(0).getTextContent();
			if(status.endsWith("success")){
				String data = root.getElementsByTagName("response").item(0).getTextContent();
				LogTools.info("data:"+data);
				JSONObject jb = new JSONObject(data);
				mEntry = getEntry(jb);

				IsSuccessful = true;
			}else{
				IsSuccessful = false;
			}

		} catch (Exception e) {
			// TODO: handle exception
			LogTools.error(e.toString());
			IsSuccessful = false;
			if(mHandler != null) mHandler.onError(0);
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(Object result) {
		// TODO Auto-generated method stub
		if (null != this.dialog && this.dialog.isShowing()) {
			this.dialog.dismiss();
		}
		
		if(IsSuccessful){
			if(mHandler != null) mHandler.onSuccessfull(mEntry);
		}
		super.onPostExecute(result);
	}
}
